package task

import (
	"apibe/grpc/rome/v1/factory"
	"apibe/grpc/rome/v1/share/config"
	"apibe/grpc/rome/v1/share/logger"
	"net/http"
	"strconv"
	"time"
)

// 脚本集合

// back task执行回调，可以根据task接口返回的信息进行报警和预处理之类的内容。
func (b *back) back(design *factory.Design, catch map[string]string, body []byte, status int, cache bool) {
	if b.FunctionName == "" {
		return
	}
	switch b.FunctionName {
	case "restart":
		if status != http.StatusOK {
			if b.Params == "" {
				for i := 0; i < 6; i++ {
					time.Sleep(time.Second * 10) // 十秒一次，如果有一次是200，就不重启
					_, _status, _, err := design.AutoAssembly(catch, time.Second*30)
					if err == nil && _status == http.StatusOK {
						return
					}
				}
				execute(config.Config.Plugin.Task.Shell["restart"]) // 一分钟内连续失败6次，就认为服务挂了，进行重启。
				logger.Logger.Panicf("server have shut down")
			} else {
				wait, err := strconv.Atoi(b.Params)
				if err != nil {
					return
				}
				time.Sleep(time.Duration(int64(wait)) * time.Minute)
				for i := 0; i < 6; i++ {
					time.Sleep(time.Second * 10) // 十秒一次，如果有一次是200，就不重启
					_, _status, _, err := design.AutoAssembly(catch, time.Second*30)
					if err == nil && _status == http.StatusOK {
						return
					}
				}
				execute(config.Config.Plugin.Task.Shell["restart"])
			}
		}
		break
	default:
		break
	}
}
